package cn.wps.sdk.demo.activity;


import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import androidx.core.content.FileProvider;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cn.wps.moffice.sdk.WpsSdk;
import cn.wps.moffice.sdk.api.common.ApiEvent;
import cn.wps.moffice.sdk.api.common.EventListener;
import cn.wps.moffice.sdk.api.common.FileApi;
import cn.wps.moffice.sdk.api.util.OpenParams;
import cn.wps.sdk.demo.base.FileItem;
import cn.wps.sdk.demo.base.SingleSelectFileActivity;

public class SingleOpenActivity extends SingleSelectFileActivity {
    @Override
    public String executeName() {
        return "打开文档";
    }

    @Override
    public void execute(List<FileItem> files) {
        openFile(files);
    }


    // 打开文档参考逻辑
    private void openFile(List<FileItem> files) {
        ArrayList<Uri> uriList = new ArrayList<>();
        for (FileItem file : files) {
            Log.d("WpsSdkLog", "filePath=" + file.filePath);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uriList.add(FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", new File(file.filePath)));
            } else {
                uriList.add(Uri.fromFile(new File(file.filePath)));
            }
        }
        if (uriList.size() == 0) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(OpenParams.OpenMode, "ReadMode");
        FileApi fileApi = WpsSdk.getInstance().getApi(FileApi.class);
        if (fileApi != null) {
            fileApi.addEventListener(SingleOpenActivity.this, ApiEvent.DocumentAfterSave, new EventListener() {
                @Override
                public void onEvent(String s, Bundle bundle) {
                    String path = bundle.getString("CurrentPath");
                    Log.d("WpsSdk", "demo onEvent: s=" + s + " bundle=" + bundle + " path=" + path);
                }
            });
            Log.d("WpsSdkLog", "demo OpenFile: filePath=" + uriList.get(0).getPath());
            fileApi.openFile(this, uriList.get(0), bundle);
        }
    }
}